package servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.UserDao;

import entity.User;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {

	private UserDao userDao = new UserDao();

	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		doPost(req, resp);
	}

	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");// 这是一个坑，前端传数据进来，要先判断它编码是否正确
		// 获取请求参数
		Boolean sucess = false;
		String uname = req.getParameter("uname");
		String pwd = req.getParameter("pwd");
		String repwd = req.getParameter("repwd");
		
		// 检查两次密码是否输入正确
		if (pwd!=null) {
			if (pwd.equals(repwd)) {
				// 密码正确后，检查用户名是否可用
				if (existsUsername(uname)) {
					// 用户名不可用
					System.out.println("用户名[" + uname + "]已存在！");
					req.getRequestDispatcher("register.jsp").forward(req, resp);
				} else {
					// 调用Service，保存到数据库，跳转到登录页面
					User user = new User();
					user.setUname(uname);
					user.setPwd(pwd);
					registUser(user);
					resp.sendRedirect("login");
				}
			} else {
				System.out.println("密码不一致");
				req.getRequestDispatcher("register.jsp").forward(req, resp);
			}
		}else {
			req.getRequestDispatcher("register.jsp").forward(req, resp);
		}
	}

	// 注册
	public void registUser(User user) {

		userDao.addUser(user);
		System.out.println("注册成功");

	}

	/**
	 * 检查 用户名是否可用
	 * 
	 * @param username
	 * @return 返回true表示用户存在，返回false表示用户名可用
	 */

	public boolean existsUsername(String uname) {

		if (userDao.queryByName(uname) == null) {
			return false;
		}
		return true;
	}

}
